import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-08-08
 * Time: 14:38
 * To BE A Better Person-2020-3-2
 */
public class TcpEchoServer {
    private ServerSocket serverSocket=null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("Server is started");
        while(true){
            //若当前没有客户端建立连接，那么就会阻塞等待
            Socket clientSocket = serverSocket.accept();

            //直接调用processconnect会导致无法接入多个客户端，所以可以采用多线程的方式来解决该问题
            //processconnect(clientSocket);
            Thread t=new Thread(()->{
                try {
                    processconnect(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
            //版本三 线程池
            //ExecutorService executorService= Executors.newCachedThreadPool();
        }
    }

    /**
     * 长连接
     * 通过这个方法给当前连上的服务器提供服务
     */
    private void processconnect(Socket clienSocket) throws IOException {
        System.out.printf("[%s:%d] 建立连接\n",clienSocket.getInetAddress().toString(),clienSocket.getPort());
        try( InputStream inputStream=clienSocket.getInputStream();OutputStream outputStream=clienSocket.getOutputStream()){
            Scanner scanner=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);
            //长连接写法
            while(true){
                if(!scanner.hasNext()){
                    //断开连接
                    break;
                }
                //1.读取请求并解析
                String request=scanner.next();
                //2.根据请求计算响应
                String respons=process(request);
                //3.将响应写回给客户端
                printWriter.println(respons);
                //刷新缓冲区
                printWriter.flush();
                System.out.printf("[%s:%d] req: %s;resp: %s\n",clienSocket.getInetAddress().toString(),clienSocket.getPort(),request,respons);

            }

        }finally {
            clienSocket.close();
        }


    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(8888);
        tcpEchoServer.start();

    }
}
